package org.ielts.action.base;

import static com.yifeng.struts2.ResultConstants.*;
import static com.yifeng.struts2.ResultParameters.setJson;
import static com.yifeng.struts2.ActionUtils.*;

import org.ielts.action.BaseAction;
import org.ielts.domain.base.Course;
import org.ielts.domain.base.CourseType;
import org.ielts.service.CourseService;
import org.ielts.service.CourseTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import com.yifeng.modules.annotations.Operation;
import com.yifeng.utils.JsonResultBuilder;

public class CourseAction extends BaseAction {

	@Autowired
	CourseService courseService;

	@Operation(result = FILL)
	public String createCourse() {

		return FILL;
	}

	@Operation(result = FILL)
	public String modifyCourse() {
		String id = form.readString("id");

		Course course = courseService.findOne(id);

		put("course", course);

		return FILL;
	}

	@Operation(result = FILL)
	public String listCourse() {

		Iterable<Course> courses = courseService.findAll();

		put("courses", courses);

		return FILL;
	}

	@Operation(result = JSON)
	public String doModifyCourse() {
		String id = form.readString("id");
		String name = form.readString("name");
		String title = form.readString("title");

		Course course = courseService.findOneByName(name);
		if (course != null && !course.getId().equals(id)) {
			setJson(JsonResultBuilder.success(false).msg("已存在同名的课程").json());
			return JSON;
		}

		courseService.modifyCourse(id, name, title);

		setJson(JsonResultBuilder.success(true).msg("修改课程成功").json());
		return JSON;
	}

	@Operation(result = JSON)
	public String doCreateCourse() {
		String name = form.readString("name");
		String title = form.readString("title");

		Course course = courseService.findOneByName(name);
		if (course != null) {
			setJson(JsonResultBuilder.success(false).msg("已存在同名的课程").json());
			return JSON;
		}

		courseService.createCourse(name, title);

		setJson(JsonResultBuilder.success(true).msg("创建课程成功").json());
		return JSON;
	}

	@Operation(result = JSON)
	public String doRemoveCourse() {
		String id = form.readString("id");
		courseService.removeCourse(id);

		setJson(JsonResultBuilder.success(true).msg("删除课程成功").json());
		return JSON;
	}
}
